package com.lw.leetcode.str.b;

/**
 * Created with IntelliJ IDEA.
 * 2384. 最大回文数字
 *
 * @author liw
 * @version 1.0
 * @date 2022/8/21 18:11
 */
public class LargestPalindromic {

    public String largestPalindromic(String num) {
        int[] arr = new int[10];
        int length = num.length();
        for (int i = 0; i < length; i++) {
            arr[num.charAt(i) - '0']++;
        }
        StringBuilder sb = new StringBuilder();
        int v = -1;
        for (int i = 9; i >= 0; i--) {
            int c = arr[i];
            if (c == 0) {
                continue;
            }
            if (v == -1 && (c & 1) == 1) {
                v = i;
            }
            if (i == 0 && sb.length() == 0) {
                continue;
            }
            c >>= 1;
            for (int j = 0; j < c; j++) {
                sb.append(i);
            }
        }
        if (sb.length() == 0 && v == -1) {
            return "0";
        }
        return sb.toString() + (v == -1 ? sb.reverse().toString() : v + sb.reverse().toString());
    }

}
